const { spawn } = require('child_process')
const fs = require('fs')
const { PYTHON } = require('../config/config')

function callWhisper(audioPath) {
  return new Promise((resolve, reject) => {
    // 1. 验证文件存在
    if (!fs.existsSync(audioPath)) {
      return reject(new Error(`音频文件不存在: ${audioPath}`))
    }

    // 2. 准备路径
    const pythonExe = PYTHON.INTERPRETER
    const scriptPath = PYTHON.SCRIPTS.WHISPER

    // 3. 启动进程
    const pyProcess = spawn(pythonExe, [scriptPath, audioPath], {
        env: { 
            ...process.env,
            // PYTHONUTF8: '1'  // 确保Python使用UTF-8编码
        }
    })

    // 4. 处理输出
    let stdout = ''
    let stderr = ''

    pyProcess.stdout.on('data', (data) => stdout += data.toString())
    pyProcess.stderr.on('data', (data) => {
      const msg = data.toString()
      if (!msg.includes('FP16')) stderr += msg  // 过滤无害警告
    })

    // 5. 处理结果
    pyProcess.on('close', (code) => {
      if (code === 0) {
        resolve(stdout.trim())
      } else {
        reject(new Error([
          `Python执行失败(code ${code})`,
          stderr || '无错误详情'
        ].join('\n')))
      }
    })

    // 6. 错误处理
    pyProcess.on('error', (err) => {
      reject(new Error(`无法启动Python进程: ${err.message}`))
    })
  })
}

module.exports = { callWhisper }